package com.life.service.impl;

import com.life.constant.MessageConstant;
import com.life.exception.AccountNotFoundException;
import com.life.exception.PasswordErrorException;
import com.life.mapper.UserMapper;
import com.life.pojo.dto.UserLoginDTO;
import com.life.pojo.dto.UserRegisterDTO;
import com.life.pojo.entity.User;
import com.life.properties.AdminProperties;
import com.life.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AdminProperties adminProperties;

    @Override
    public User login(UserLoginDTO userLoginDTO) {
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();
        if (!adminProperties.getUsername().equals(username)) {
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        if (!adminProperties.getPassword().equals(password)) {
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        User user = new User();
        user.setId(0L);
        user.setUsername(username);
        return user;
    }

    @Override
    public void register(UserRegisterDTO userRegisterDTO) {
        String password = DigestUtils.md5DigestAsHex(userRegisterDTO.getPassword().getBytes());
        userRegisterDTO.setPassword(password);
        User user = new User();
        BeanUtils.copyProperties(userRegisterDTO, user);
        userMapper.insert(user);
    }
}
